//
//  FirstViewController.swift
//  MySpots
//
//  Created by stu on 2019/11/4.
//  Copyright © 2019年 stu. All rights reserved.
//

import UIKit
import CoreLocation

class CurrentLocationViewController: UIViewController,CLLocationManagerDelegate {
    
    
    @IBOutlet weak var messageLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var addressLabel: UILabel!
    @IBOutlet weak var tagButton: UIButton!
    @IBOutlet weak var getButton: UIButton!
    
    let locationManger = CLLocationManager()
    var location : CLLocation?
    var lastLocationError: Error?
    var updatingLocation = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        updateUI()
        updateGetButton()
    }
    func updateGetButton(){
        if updatingLocation{
            getButton.setTitle("停止定位", for: .normal)
        }else{
            getButton.setTitle("我的位置", for: .normal)
        }
    }
    
    fileprivate func startLocationManager(){
        if CLLocationManager.locationServicesEnabled(){
            locationManger.delegate = self
            locationManger.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManger.startUpdatingLocation()
            updatingLocation = true
        }
        
    }

    @IBAction func getLocation(_ sender: Any) {
        let authStatu = CLLocationManager.authorizationStatus()
        if authStatu == .notDetermined{
            locationManger.requestWhenInUseAuthorization()
            return
        }
        if authStatu == .denied || authStatu == .restricted{
            let alert = UIAlertController(title: "定位服务已关闭", message: "请通过设置允许应用使用定位服务", preferredStyle: .alert)
            let action = UIAlertAction(title: "确定", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
        if updatingLocation{
            stopLocationManager()
        }else{
            location = nil
            lastLocationError = nil
            startLocationManager()
        }
     
        updateUI()
        updateGetButton()
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let newLocation = locations.last!
        print("UpdateLocations\(newLocation)")
        if newLocation.timestamp.timeIntervalSinceNow < -5{
            return
        }
        if newLocation.horizontalAccuracy < 0{
            return
        }
        if location == nil || location!.horizontalAccuracy > newLocation.horizontalAccuracy{
            location = newLocation
            lastLocationError = nil
            updateUI()
            if newLocation.horizontalAccuracy <= locationManger.desiredAccuracy{
                stopLocationManager()
                updateGetButton()
            }
        }
        
        
    }
    func updateUI(){
        if let location = location{
            latitudeLabel.text = String(format: "%.8f", location.coordinate.latitude)
            longitudeLabel.text = String(format: "%.8f", location.coordinate.longitude)
            tagButton.isHidden = false
            messageLabel.text = ""
        }else{
            latitudeLabel.text = ""
            longitudeLabel.text = ""
            addressLabel.text = ""
            tagButton.isHidden = true
            
            let statusMessage: String
            if let error = lastLocationError as NSError?{
                if error.domain == kCLErrorDomain && error.code == CLError.denied.rawValue{
                    statusMessage = "定位不可用"
                }else{
                    statusMessage = "定位服务出错"
                }
            }else if !CLLocationManager.locationServicesEnabled(){
                statusMessage = "定位不可用"
            }else if updatingLocation{
                statusMessage = "玩命定位中..."
            }else{
                statusMessage = "点击‘我的位置’进行定位"
            }
            messageLabel.text = statusMessage
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("FailWithError\(error)")
        if (error as NSError).code == CLError.locationUnknown.rawValue{
            return
        }
        lastLocationError = error
        stopLocationManager()
        updateUI()
        updateGetButton()
    }
    func stopLocationManager(){
        if updatingLocation{
            locationManger.stopUpdatingLocation()
            locationManger.delegate = nil
            updatingLocation = false
        }
    }

}

